const { getModelType, diagonalLength } = require('../../util/utils')
const { ignoreIt } = require('../../util/ignore')
const { parseProjectile } = require('../projectile/parse')
const { parseEmission } = require('../emission/emission')
const { parseAttackBehavior } = require('./behavior')
const { Display, translateValue, translateAttack } = require('../../display/general')
const { translateFilters } = require('../../display/filters')

function parseAttack(attack) {
    let result = []
    let isBird = false // for bottom beast
    let attackTemplate = {
        name: attack.weapons && attack.weapons.length <= 1 ? translateAttack(attack.name) : null,
        numberOfAttack: null,
        range: (attack.range >= diagonalLength) ? '∞' : attack.range,
        projectile: [],
        attackCooldown: null,
        minAttackCooldown: null,
        startCooldown: null,
        meta: {},
        behaviors: [],
        filters: [],
        notes: [
            attack.attackThroughWalls ? translateValue('ignoreObstacles', 'can target through walls') : null,
        ]
    }
    if (attack.behaviors) {
        attack.behaviors.forEach(b => {
            const type = getModelType(b)
            if (ignoreIt(type)) return
            if (type === 'GyrfalconPatternModel') isBird = true
            parseAttackBehavior(b, attackTemplate, type)
        })
    }
    attackTemplate.filters = translateFilters(attackTemplate.filters)
    if (isBird && attack.weapons && attack.weapons.length === 0) {
        result.push(attackTemplate)
    }
    attack.weapons.forEach(w => {
        let a = structuredClone(attackTemplate)
        if (!a.name) {
            a.name = translateAttack(w.name)
        }
        a.attackCooldown = Display.time(w.rate)
        a.startCooldown = w.startInCooldown ? Display.time(w.customStartCooldown) : null
        a.notes.push(w.fireWithoutTarget ? translateValue('autoAttack', 'auto attacks') : null)
        a.projectile.push(parseProjectile(w.projectile))
        parseEmission(w.emission, a.projectile[0], a)
        if (w.behaviors) {
            w.behaviors.forEach((b => {
                const type = getModelType(b)
                if (ignoreIt(type)) return
                parseAttackBehavior(b, a, type)
            }))
        }
        result.push(a)
    })
    return result
}

module.exports = {
    parseAttack
}